package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.GetUserInfoUtil;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.org.vo.LoginVO;
import cn.itsource.org.vo.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Optional;

@Service
//Propagation.SUPPORTS:支持别人事务
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee, EmployeeQuery> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     *
     * redis + token
     * @param employee
     * @return
     */
    @Override
    public AjaxResult login(Employee employee) {

        //1.根据用户名查询对象(email,phone,username),如果没有提示用户名不存在
        //有老盐  还有加密的密码
        Employee dbEmployee = employeeMapper.selectInfo(employee.getUsername());
        Optional.ofNullable(dbEmployee).orElseThrow(() -> new BusinessException("账号问题,账户名与密码不匹配，请重新输入"));

        //2.比对密码  (加盐(数据库老盐) 加密(md5))
        //传进来的password
        String password = employee.getPassword();
        String md5Password = MD5.create().setSalt(dbEmployee.getSalt().getBytes()).digestHex(password);

        //和数据库的之前就加密好的进行比对
        if (!StringUtils.equals(dbEmployee.getPassword(),md5Password)){
            throw  new BusinessException("密码问题,账户名与密码不匹配，请重新输入");
        }

        //copy
        UserInfo userInfo = BeanUtil.copyProperties(dbEmployee, UserInfo.class);

        //3.把数据保存到redis key :token (搞个uuid就行了)  封装vo对象(返回前端的专用对象)
        String token = IdUtil.fastSimpleUUID();
        redisService.setStringKeyAndValue(token,userInfo,30);

        //封装返回的页面vo数据
        LoginVO loginVO = new LoginVO(token, userInfo);

        //loginVo封装回去
        return AjaxResult.createSuccess(loginVO);
    }

    @Override
    public List<Employee> shopEmployees() {

        //获取到shopId
        Long shopId = GetUserInfoUtil.getShopId();

        return employeeMapper.employeeMapper(shopId);
    }

    //基础查询由继承得到

}
